
const hasLocalStorage = function() {
    const x = "F5v6#VQR5%";
    try {
        localStorage.setItem(x, x);
        localStorage.removeItem(x);
        return true;
    } catch (e) {
        return false;
    }
}();

const NO_STORAGE = {
    getItem: () => null,
    setItem: () => false,
    removeItem: () => false,
};

/**
 * @param {Storage} storage
 * @returns {Stash} wrapped storage
 */
function newStash(storage) {
    return new class Stash {

        /**
         * @param {string} key
         * @returns {string|null} the value if the entry exists, otherwise null
         */
        get(key) {
            return storage.getItem(key);
        }

        /**
         * @param {string} key
         * @param {string|null} value
         * @returns {boolean} true if the k/v pair was successfully stored (or removed if the value is null)
         */
        put(key, value) {
            try {
                return (value === null ? storage.removeItem(key) : storage.setItem(key, value)) === undefined;
            } catch (ignored) {
                return false;
            }
        }

    };
}

export const localStash = newStash(hasLocalStorage ? localStorage : NO_STORAGE);
